package com.gymmsystem.GYMMSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gymmsystem.GYMMSystem.entity.User;
import com.gymmsystem.GYMMSystem.mapper.UserMapper;
import com.gymmsystem.GYMMSystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getUserLevel(Long userId) {
        User user = getUserById(userId);
        if (user == null) {
            return "普通用户";
        }

        Integer points = user.getUPoints();
        if (points == null) {
            return "普通用户";
        }

        // 用户等级规则
        if (points >= 400) {
            return "高级会员";
        } else if (points >= 100) {
            return "中级会员";
        } else if (points >= 1) {
            return "初级会员";
        } else {
            return "普通用户";
        }
    }

    @Override
    public boolean canUserReserveCourse(Long userId, String courseGrade) {
        String userLevel = getUserLevel(userId);

        // 预约权限规则
        switch (userLevel) {
            case "高级会员":
                return true; // 可以预约所有课程
            case "中级会员":
                return "初级".equals(courseGrade) || "中级".equals(courseGrade);
            case "初级会员":
                return "初级".equals(courseGrade);
            case "普通用户":
            default:
                return false;
        }
    }

    @Override
    public User login(String mobile, String password) {
        // 验证手机号格式
        if (!isValidMobile(mobile)) {
            throw new RuntimeException("手机号格式不正确");
        }

        // 根据手机号查询用户
        User user = userMapper.findByMobile(mobile);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码（这里简单比较，实际应该加密比较）
        if (!password.equals(user.getUPw())) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }

    @Override
    public boolean register(User user) {
        // 基本参数验证
        if (user == null || user.getUMobile() == null || user.getUPw() == null) {
            throw new RuntimeException("手机号和密码不能为空");
        }

        // 验证手机号格式
        if (!isValidMobile(user.getUMobile())) {
            throw new RuntimeException("手机号格式不正确");
        }

        // 验证密码长度
        if (user.getUPw().length() < 6) {
            throw new RuntimeException("密码长度不能少于6位");
        }

        // 检查手机号是否已存在
        if (checkMobileExists(user.getUMobile())) {
            throw new RuntimeException("该手机号已注册");
        }

        // 设置默认值
        if (user.getUNickname() == null || user.getUNickname().trim().isEmpty()) {
            // 使用手机号后4位作为默认昵称
            String mobile = user.getUMobile();
            user.setUNickname("用户" + mobile.substring(mobile.length() - 4));
        }

        if (user.getUPoints() == null) {
            user.setUPoints(0);
        }

        if (user.getURt() == null) {
            user.setURt(0);
        }

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);

        // 插入用户记录
        int result = userMapper.insert(user);
        return result > 0;
    }

    @Override
    public User getUserById(Long userId) {
        if (userId == null) {
            return null;
        }
        return userMapper.findUserById(userId);
    }

    @Override
    public boolean updateUserNickname(Long userId, String nickname) {
        if (userId == null || nickname == null || nickname.trim().isEmpty()) {
            return false;
        }

        // 验证用户是否存在
        User user = userMapper.findUserById(userId);
        if (user == null) {
            return false;
        }

        int result = userMapper.updateUserNickname(userId, nickname.trim());
        return result > 0;
    }

    @Override
    public boolean checkMobileExists(String mobile) {
        if (mobile == null) {
            return false;
        }
        return userMapper.countByMobile(mobile) > 0;
    }

    /**
     * 验证手机号格式
     */
    private boolean isValidMobile(String mobile) {
        if (mobile == null || mobile.length() != 11) {
            return false;
        }
        // 简单的手机号格式验证（11位数字，1开头）
        return Pattern.matches("^1[3-9]\\d{9}$", mobile);
    }

    /**
     * 获取用户排行榜（按积分降序排序）
     */
    @Override
    public List<User> getUserRanking() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("u_points");
        // 直接使用 baseMapper
        return userMapper.selectList(queryWrapper);
    }

    /**
     * 新增：更新用户积分和剩余天数
     */
    @Override
    public boolean updateUserInfo(Long userId, Integer points, Integer remainingDays) {
        if (userId == null) {
            return false;
        }

        // 验证用户是否存在
        User user = userMapper.findUserById(userId);
        if (user == null) {
            return false;
        }

        // 参数验证
        if (points == null || points < 0) {
            points = user.getUPoints(); // 保持原值
        } 
        // 移除积分累加逻辑，直接使用传入的points值进行覆盖
        
        if (remainingDays == null || remainingDays < 0) {
            remainingDays = user.getURt(); // 保持原值
        } 
        // 移除剩余天数累加逻辑，直接使用传入的remainingDays值进行覆盖
        
        int result = userMapper.updateUserInfo(userId, points, remainingDays);
        return result > 0;
    }

    /**
     * 新增：删除用户
     */
    @Override
    public boolean deleteUser(Long userId) {
        if (userId == null) {
            return false;
        }

        // 验证用户是否存在
        User user = userMapper.findUserById(userId);
        if (user == null) {
            return false;
        }

        try {
            // 使用 MyBatis-Plus 的删除方法
            int result = userMapper.deleteById(userId);
            return result > 0;
        } catch (Exception e) {
            log.error("删除用户失败，用户ID: {}", userId, e);
            return false;
        }
    }
    
    /**
     * 新增：更新用户完整信息
     */
    @Override
    public boolean updateUserProfile(Long userId, String nickname, String mobile, String oldPassword, String newPassword) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 验证用户是否存在
        User user = userMapper.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 如果要修改手机号，验证手机号格式
        if (mobile != null && !mobile.isEmpty() && !mobile.equals(user.getUMobile())) {
            if (!isValidMobile(mobile)) {
                throw new RuntimeException("手机号格式不正确");
            }
            // 检查新手机号是否已被使用
            if (checkMobileExists(mobile)) {
                throw new RuntimeException("该手机号已被注册");
            }
        } else {
            // 如果不修改手机号，使用原手机号
            mobile = user.getUMobile();
        }
        
        // 如果要修改密码，必须验证原密码
        String finalPassword = user.getUPw();
        if (newPassword != null && !newPassword.isEmpty()) {
            if (oldPassword == null || oldPassword.isEmpty()) {
                throw new RuntimeException("修改密码时必须输入原密码");
            }
            
            // 验证原密码
            if (!verifyPassword(userId, oldPassword)) {
                throw new RuntimeException("原密码错误");
            }
            
            // 验证新密码长度
            if (newPassword.length() < 6) {
                throw new RuntimeException("新密码长度不能少于6位");
            }
            
            finalPassword = newPassword;
        }
        
        // 使用原昵称或新昵称
        String finalNickname = (nickname != null && !nickname.isEmpty()) ? nickname : user.getUNickname();
        
        // 执行更新
        int result = userMapper.updateUserProfile(userId, finalNickname, mobile, finalPassword);
        return result > 0;
    }
    
    /**
     * 验证用户密码
     */
    @Override
    public boolean verifyPassword(Long userId, String password) {
        if (userId == null || password == null) {
            return false;
        }
        
        int count = userMapper.verifyPassword(userId, password);
        return count > 0;
    }
    
    @Override
    public boolean addUserPointsAndDays(Long userId, Integer addPoints, Integer addDays) {
        if (userId == null) {
            return false;
        }
        
        // 验证用户是否存在
        User user = userMapper.findUserById(userId);
        if (user == null) {
            return false;
        }
        
        // 计算新的积分和天数，实现叠加逻辑
        Integer currentPoints = user.getUPoints() != null ? user.getUPoints() : 0;
        Integer currentDays = user.getURt() != null ? user.getURt() : 0;
        
        // 只有当传入的参数大于0时才进行叠加
        Integer newPoints = (addPoints != null && addPoints > 0) ? (currentPoints + addPoints) : currentPoints;
        Integer newDays = (addDays != null && addDays > 0) ? (currentDays + addDays) : currentDays;
        
        // 调用现有的updateUserInfo方法进行更新
        return userMapper.updateUserInfo(userId, newPoints, newDays) > 0;
    }
}